﻿using System;
using System.Web.UI.WebControls;

namespace ECommerce.Administration.Controls
{
	public partial class RolesList : AdminBaseUsercontrol
	{
		protected class Role
		{
			public Role() { }
			public Role(string name, string desc) { RoleName = name; Description = desc; }

			public string RoleName { get; set; }
			public string Description { get; set; }
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				BindRoles();
			}
		}

		protected void GridRoles_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
		{
			if(e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.Header)
			{
				e.Row.Cells[1].Text = GetLocalResourceString("Admin.RolesList.NameHeader");
				e.Row.Cells[2].Text = GetLocalResourceString("Admin.RolesList.DescriptionHeader");
			}
		}

		private void BindRoles()
		{
			var roles = System.Web.Security.Roles.GetAllRoles();

			System.Collections.Generic.List<Role> data = new System.Collections.Generic.List<Role>();
			
			foreach(var r in roles)
			{
				data.Add(new Role(r, string.Empty));
			}

			GridRoles.DataSource = data;
			GridRoles.DataBind();
		}

		public void DeleteSelectedRoles()
		{
			foreach(System.Web.UI.WebControls.GridViewRow rowItem in GridRoles.Rows)
			{
				var chBox = rowItem.FindControl("cbRole") as CheckBox;
				var rowName = rowItem.FindControl("hfRoleName") as HiddenField;

				bool isChecked = chBox.Checked;
				string roleName = rowName.Value;

				if(isChecked)
				{
					System.Web.Security.Roles.DeleteRole(roleName);
				}
			}

			BindRoles();
		}
	}
}